package cn.vcjf.washcar.api.order.service.impl;

import cn.vcjf.washcar.api.order.entity.WashCarOrder;
import cn.vcjf.washcar.api.order.service.WashCarOrderService;
import cn.vcjf.washcar.common.util.DateUtils;
import cn.vcjf.washcar.common.util.weixin.WechatUtils;
import cn.vcjf.washcar.common.wxpay.AbstractWxpayCallback;
import cn.vcjf.washcar.dict.entity.Dict;
import cn.vcjf.washcar.dict.mapper.DictMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.util.List;

/**
 * @Auther: zhengzihang
 * @Date: 2018/7/24 10:27
 * @Description:
 */
@Service
public class WxpayCallbackServiceImpl extends AbstractWxpayCallback<WashCarOrder> {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private WashCarOrderService washCarOrderService;
	@Resource
	private DictMapper dictMapper;
	@Value("${wx.message.openId}")
	private String def_openId;

	private String openId;
	@Value("${wx.template.id}")
	private String templat_id;

	@Value("${wx.template.id}")
	private String def_templat_id;

	@Value("${server.domain.name}")
	private String domain;

//	private String clickurl="wash-car-api/order/washCarOrder/orderDetail?id=";
	private String clickurl="vc-washcar-manager/washcarorder/washCarOrder/orderDetail.do?id=";

	@Value("${APP_NAME}")
	private String APP_NAME;

	private String topcolor="#173177";//模板字体的颜色;

	@Value("${manager.openid}")
	protected String managerOpenId;

	public void getOpenId(){
		EntityWrapper<Dict> wrapper = new EntityWrapper<Dict>();
		wrapper.eq("type", managerOpenId);
		Dict dict= null;
		List<Dict> dicts = dictMapper.selectList(wrapper);
		if(dicts!=null&&!dicts.isEmpty()){
			this.openId = dicts.get(0).getValue();
		}else {
			this.openId = def_openId;
			logger.info("在字典中获取商户openId失败,使用默认配置:{}",def_openId);
		}
	}
	@Scheduled(cron = "0 */5 * * * ?")//每5分钟都执行
	public void checkOpenIDandTemplatId(){
		logger.info("5分钟已到,自动刷新openId和:templat_id");
		this.openId = null;
		this.templat_id = null;
	}

	public void getTemplatId(){
		EntityWrapper<Dict> wrapper = new EntityWrapper<Dict>();
		wrapper.eq("type", "WX_TEMPLAT_MSG_ID");
		Dict dict= null;
		List<Dict> dicts = dictMapper.selectList(wrapper);
		if(dicts!=null&&!dicts.isEmpty()){
			this.templat_id = dicts.get(0).getValue();
		} else {
			this.templat_id = def_templat_id;
			logger.info("在字典中获取商户templat_id失败,使用默认配置:{}",def_templat_id);
		}
	}

	@Override
	public void cleanOpenId(){
		this.openId = null;
	}

	@Override
	protected void doOrderSuccess(WashCarOrder order, String res, String pOrderId) throws ServletException {

		washCarOrderService.updateWashOrderStatus(order, WashCarOrder.ORDER_PAY_OK, res, pOrderId);
		String first=APP_NAME+"用户支付成功提醒";
		String orderMoneySum=order.getMoney()+"元";

		String merchantName=order.getUserName()+"("+order.getUserPhone()+")";
		String payTime=DateUtils.formatDateTime(order.getPayTime());
		String orderNo=order.getOrderNo();
		String remark="订单信息:车型:"+order.getCarInfo();

		JSONObject data = WechatUtils.packJsonmsg(first,
				 merchantName,
				 orderMoneySum,
				 payTime,
				 orderNo,
				 remark,
				topcolor);
		//获取openid
		if(StringUtils.isBlank(openId)){
			this.getOpenId();
		}
		//获取openid
		if(StringUtils.isBlank(templat_id)){
			this.getTemplatId();
		}
		logger.info("openId==========={}\ntemplat_idopenId==========={}\nclickurl==========={}",openId,templat_id,domain + clickurl + order.getId());
		JSONObject object = WechatUtils.sendWechatmsgToUser(openId, templat_id, domain + clickurl + order.getId(), topcolor, data);
		logger.info(object.toJSONString());
	}

	@Override
	protected void doOrderFailed(WashCarOrder order, String res) throws ServletException {

		washCarOrderService.updateWashOrderStatus(order, WashCarOrder.ORDER_PAY_FAIL, res, null);
	}

	@Override
	protected void doOrderUnding(WashCarOrder order, String res) throws ServletException {
		washCarOrderService.updateWashOrderStatus(order, WashCarOrder.ORDER_UNDING, res, null);
	}

	@Override
	protected WashCarOrder findOrder(String orderNo) {
		EntityWrapper<WashCarOrder> wrapper = new EntityWrapper<WashCarOrder>();
		wrapper.eq("o.orderNo", orderNo);

		return washCarOrderService.selectWashCarOrderOne(wrapper);
	}

	@Override
	protected Long getOrderStatus(WashCarOrder order) {
		return order.getStatus().longValue();
	}

	@Override
	protected Long getSuccessStatusStatus() {
		return WashCarOrder.ORDER_PAY_OK + 0L;
	}
}
